package com.dxy.lc.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dxy.lc.base.Resp;
import com.dxy.lc.base.StatusMessageEnum;
import com.dxy.lc.base.UnifiedException;
import com.dxy.lc.enums.UserStatus;
import com.dxy.lc.model.entity.User;
import com.dxy.lc.service.UserService;
import com.dxy.lc.socketio.ISessionService;
import com.dxy.lc.utils.LoginUtil;
import com.dxy.lc.utils.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

@Slf4j
@RestController
@RequestMapping("/lc/auth")
public class AuthController {


    @Autowired
    private UserService userService;
    @Autowired
    private ISessionService sessionService;

    @PostMapping("/login")
    public Resp<String> login(@RequestBody User user) {
        User dbUser = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, user.getUsername()));
        if (dbUser == null) {
            throw new UnifiedException(500, "用户{}不存在", user.getUsername());
        }

        if (!Objects.equals(MD5Util.getEncryptPassword(user.getPassword()), dbUser.getPassword())) {
            throw new UnifiedException(StatusMessageEnum.PWD_ERROR);
        }

        String token = LoginUtil.createToken(String.valueOf(dbUser.getId()));
        LoginUtil.setTokenCache(String.valueOf(dbUser.getId()), token);
        return Resp.bizSuccess(token);
    }

    @GetMapping("/checkLogin")
    public Resp<Boolean> checkLogin(){
        // 此处会经过拦截器AuthInterceptor
        return Resp.bizSuccess(Boolean.TRUE);
    }

    @GetMapping("/logout")
    public Resp logout(){
        String loginUserId = LoginUtil.getLoginUserIdOrException();
        LoginUtil.delCachedToken(loginUserId);
        sessionService.removeSessionByUserId(loginUserId);
        return Resp.bizSuccess();
    }

}
